package com.itfreer.bpm.workflow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.bpm.config.service.IBpmConfigService;
import com.itfreer.bpm.config.service.IBpmTaskConfigService;
import com.itfreer.bpm.flow.api.IBpmProjectEntity;
import com.itfreer.bpm.flow.api.IUserNextTaskUser;
import com.itfreer.bpm.history.entity.BpmHistoryEntity;
import com.itfreer.bpm.messager.BpmMessage;
import com.itfreer.bpm.option.para.NextTaskInfo;
import com.itfreer.bpm.option.para.OptionInfo;
import com.itfreer.bpm.option.para.OptionType;
import com.itfreer.bpm.option.para.TaskInfo;
import com.itfreer.bpm.option.para.TaskType;
import com.itfreer.bpm.power.para.UserInfo;
import com.itfreer.bpm.workflow.drive.IWorkFlowDrive;
import com.itfreer.bpm.workflow.option.SignCommonTask;
import com.itfreer.bpm.workflow.option.SignMultiTask;
import com.itfreer.bpm.workflow.userrole.IUserRole;
import com.itfreer.bpm.workflow.utils.BpmApprovalHistoryUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryEditUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryQueryUtil;
import com.itfreer.bpm.workflow.utils.BpmNextTaskUtils;
import com.itfreer.bpm.workflow.utils.BpmUserAuthUtils;

/**
 * 流程退回和提交的通用操作模块
 * @author gj
 *
 */
@Component
public class BpmWorkFlowCommonSignImp {

	/**
	 * 流程驱动服务
	 */
	@Autowired
	protected IWorkFlowDrive workFlowDrive;
	
	/**
	 * 构建历史帮转工具
	 */
	@Autowired
	BpmHistoryEditUtil historyEditUtl;
	
	/**
	 * 构建用户审批历史
	 */
	@Autowired
	BpmApprovalHistoryUtil approvalUtil;
	
	/**
	 * 用户授权工具
	 */
	@Autowired
	BpmUserAuthUtils userAuthUtils;
	
	/**
	 * 审批过程查询接口
	 */
	@Autowired
	BpmHistoryQueryUtil historyQueryUtil;
	
	/**
	 * 用户角色接口
	 */
	@Autowired
	IUserRole userRole;
	/**
	 * 用户自定义操作下一步审批人接口
	 */
	@Autowired(required=false)
	IUserNextTaskUser userNextTaskUser;
	
	/**
	 * 下一个环节工具
	 */
	@Autowired
	BpmNextTaskUtils nextTaskUtils;
	
	/**
	 * 单节点会签提交
	 */
	@Autowired
	SignMultiTask signmultiTask;
	
	/**
	 * 多节点选择节点
	 */
	@Autowired
	SignCommonTask signCommonTask;
	
	/**
	 * 项目退回功能的节点开发配置
	 */
	public BpmMessage signTask(OptionInfo oInfo, IBpmProjectEntity entity, UserInfo user,String optionName) {
		BpmMessage message=new BpmMessage();
		
		HashMap<String,Object> work_where=new HashMap<String,Object>();
		work_where.put("sexeid:=", oInfo.getSexeid());
		//检查校验是否是超级管理员
		if(!user.isSuperAdmin()) {
			work_where.put("toptassigneese:like",user.getUserId());
		}
		List<BpmHistoryEntity>toWorkList= historyQueryUtil.getWorkEntitys(null, work_where, null, 1000, 1);
		//检查项目是否拥有权限
		if(toWorkList==null || toWorkList.size()<1) {
			message.setStatus(false);
			message.setMessage("没有项目审核的权限");
			return message;
		}
		HashMap<String, Object> allWrok=new HashMap<String,Object>(); 
		allWrok.put("sexeid:=", oInfo.getSexeid());
		List<BpmHistoryEntity>allToWork= historyQueryUtil.getWorkEntitys(null, allWrok, null, 1000, 1);
		String bestHistoryStatus="21";
		if(allToWork.size()==toWorkList.size()) {
			bestHistoryStatus="21";
		}else {
			bestHistoryStatus="2";
		}
		
		//查询最新的项目记录
		String o_sassignees="";
		HashMap<String,Object> overwork_where=new HashMap<String,Object>();
		overwork_where.put("sexeid:=", oInfo.getSexeid());
		BpmHistoryEntity overWrokH=historyQueryUtil.getOverWorkEntitys(null, overwork_where, null, 1, 1).get(0);
		o_sassignees=overWrokH.getsassignees();
		
		//处理项目来源问题
		String fromTaskName="";
		String fromTaskID="";
		if(toWorkList.size()==1) {
			fromTaskName=toWorkList.get(0).gettaskdefname();
			fromTaskID=toWorkList.get(0).gettaskdefid();
		}else {
			boolean imulti=true;
			for(BpmHistoryEntity iwork:toWorkList) {
				if(iwork.getTasktype().equals(TaskType.CommonTask)) {
					imulti=false; 
				}
				if(fromTaskName==null) {
					fromTaskName=iwork.gettaskdefname();
					fromTaskID=iwork.gettaskdefid();
				}else {
					if(!fromTaskID.contains(iwork.gettaskdefid())) {
						fromTaskName=","+iwork.gettaskdefname();
						fromTaskID=","+iwork.gettaskdefid();
					}
				}
			}
			if(imulti) {
				fromTaskName=toWorkList.get(0).gettaskdefname();
				fromTaskID=toWorkList.get(0).gettaskdefid();
			}
		}
		
		//处理提交操作(工作流需要这些操作)
		HashMap<String, Object>ComValue=new HashMap<String, Object>();
		if(oInfo.getNextTask()!=null && oInfo.getNextTask().size()>0) {
			for(TaskInfo itask: oInfo.getNextTask()) {
				if(itask.isTaskSelect()) {
					ComValue.put(itask.getTaskdefinedid(), optionName);
				}
			}
		}
		
		//保存已经产生的历史项目
		//处理前端不带回审批历史问题的表单问题
		List<BpmHistoryEntity> lst=oInfo.getEditHistory();
		if(lst==null || lst.size()<1) {
			for(BpmHistoryEntity iwork:toWorkList) {
				lst.add(iwork);
			}
		}
		boolean findNewest=false;
		
		boolean isEndProcess=false;
		for(BpmHistoryEntity history : lst) {
			
			if(history.gethistorystatus()!=null 
					&& history.gethistorystatus().trim().contains("2")) {
				findNewest=true;
			}
			
			history.setoptresult(optionName);
			history.setoptassigneesid(user.getUserId());
			history.setoptassigneesname(user.getUserName());
			history.setoptorgid(user.getUserOrgCode());
			history.setoptorgname(user.getUserOrgName());
			history.setopttime(new Date());
			history.sethistorystatus("0");
			
			if(oInfo.getNextTask()==null || oInfo.getNextTask().size()<1) {
				if("结束".equals(history.getNexttask())) {
					isEndProcess=true;
				}
			}
			
		}
		historyEditUtl.updateList(lst);
		
		//没有查询到最新的记录(已办项逻辑，所有创建的第一条记录为永远的待办记录)
		if(!findNewest) {
			if("21".equals(overWrokH.gethistorystatus())) {
				overWrokH.sethistorystatus("1");
			}else if("20".equals(overWrokH.gethistorystatus())){
				overWrokH.sethistorystatus("0");
			}else {
			}
			historyEditUtl.updateEntity(overWrokH);
		}
		if(oInfo.getOptiontype().equals(OptionType.MuliSingleSign)) {
			this.signmultiTask.signTask(oInfo, entity, user, o_sassignees, overWrokH, fromTaskName, fromTaskID, ComValue,bestHistoryStatus);
		}else if(oInfo.getOptiontype().equals(OptionType.CommonSign)
				|| oInfo.getOptiontype().equals(OptionType.InclusiveSign)
				|| oInfo.getOptiontype().equals(OptionType.ExclusiveSign)
				|| oInfo.getOptiontype().equals(OptionType.ParallelSign)
				|| oInfo.getOptiontype().equals(OptionType.CommonBack)){
			this.signCommonTask.signTask(oInfo, entity, user, o_sassignees, overWrokH, fromTaskName, fromTaskID, ComValue,bestHistoryStatus);
		}else if(isEndProcess) {
			this.signCommonTask.publishedProcess(oInfo, entity, user, o_sassignees, overWrokH, fromTaskName, fromTaskID, ComValue,bestHistoryStatus);
		}
		return message;
	}
}
